import store from '../store/index.js';
export default {
	config: {
		baseURL: "http://ceshi8.dishaxy.com",
		appid: "bd9d01ecc75dbbaaefce",
		//请求拦截器
		beforeRequest(options = {}) {
			return new Promise((resolve, reject) => {
				console.log('请求拦截器')
				// 公共参数处理
				options.url = this.baseURL + options.url
				options.method = options.method || 'GET'
				options.header = {
					appid: this.appid,
					token: store.state.token
				}
				
				// 权限的相关验证
				resolve(options)
			})
		},
		//响应拦截器
		beforResponse([error, res]){
			return new Promise((resolve, reject)=>{
				console.log('响应拦截器')
				// 错误提示处理
				if (res.statusCode != 200 || res.data.msg == 'fail') {
					let msg = res.data.data || '求情失败'
					uni.showToast({
						title: msg,
						icon: 'none'
					});
					return reject(msg)
				}
				resolve(res.data.data)
			})
		}
	},
	request(options = {}) {
		return this.config.beforeRequest(options)
		.then(opt => uni.request(opt))
		.then(this.config.beforResponse)
	},
	// GET请求
	get(url, params = null, options = {}){
		options.url = url
		options.url += params ? ('?' + Object.keys(params).map(key=>key+'='+params[key]).join('&')) : ''
		options.method = 'GET'
		return this.request(options)
	},
	// POST请求
	post(url, data = {}, options = {}){
		options.url = url
		options.method = 'POST'
		options.data = data
		return this.request(options)
	}
}
